﻿using System;
using System.Net;
using System.Text;
using TFSExceptionHandling.Domain.PushNotification;

namespace TFSExceptionHandling.DistributedServices.Push
{
    public class Notification : INotification
    {
        private static Uri _uri;

        public void Subscribe(string subscriberUri)
        {
            _uri = new Uri(subscriberUri);
        }

        public void SendTile(string title, string message)
        {
            string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            "<wp:Notification xmlns:wp=\"WPNotification\">" +
                "<wp:Tile>" +
                    "<wp:Title>" + title + "</wp:Title>" +
                    "<wp:Count>" + message + "</wp:Count>" +
                "</wp:Tile>" +
            "</wp:notification>";

            byte[] messageBytes = Encoding.UTF8.GetBytes(tileMessage);
            SendMessage(_uri, messageBytes, "tileMessage");
        }

        public void SendToast(string title, string message)
        {
            string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                    "<wp:Toast>" +
                        "<wp:Text1>" + title + "</wp:Text1>" +
                        "<wp:Text2>" + message + "</wp:Text2>" +
                    "</wp:Toast>" +
                "</wp:Notification>";

            byte[] messageBytes = Encoding.UTF8.GetBytes(toastMessage);
            SendMessage(_uri, messageBytes, "toastMessage");
        }

        private static void SendMessage(Uri uri, byte[] message, string notificationType)
        {
            
            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "text/xml";
            request.ContentLength = message.Length;

            switch (notificationType)
            {
                case "tileMessage":
                    request.Headers.Add("X-WindowsPhone-Target", "token");
                    request.Headers.Add("X-NotificationClass", "1");
                    break;
                case "toastMessage":
                    request.Headers.Add("X-WindowsPhone-Target", "toast");
                    request.Headers.Add("X-NotificationClass", "2");
                    break;
            }

            var requestStream = request.GetRequestStream();
            requestStream.Write(message, 0, message.Length);
        }
    }
}
